package com.shuhua.taskServer.controller;

import com.shuhua.pojo.entity.Task;
import com.shuhua.taskServer.service.TaskService;
import com.shuhua.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private TaskService taskService;

    private static final String[] TASK_FIELDS = {"task_id", "title", "task_type", "description", "address", "start_time", "end_time", "budget", "dispatch_mode", "priority_level", "status", "created_at", "updated_at", "remark"};
    private static final String[] CRAFTSMAN_FIELDS = {"craftsman_username", "craftsman_phone", "craftsman_real_name", "craftsman_department", "craftsman_station", "craftsman_avatar"};

    @PostMapping
    public Result<?> add(@RequestBody Task task) {
        taskService.save(task);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        taskService.removeById(id);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Task task) {
        taskService.updateById(task);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<Task> get(@PathVariable Long id) {
        Task task = taskService.getById(id);
        return Result.success(task);
    }

    @GetMapping("/list")
    public Result<List<Task>> list() {
        List<Task> list = taskService.list();
        return Result.success(list);
    }

    private Map<String, Object> wrapTask(Map<String, Object> map) {
        if (map == null) return null;
        java.util.LinkedHashMap<String, Object> result = new java.util.LinkedHashMap<>();
        java.util.LinkedHashMap<String, Object> craftsman = new java.util.LinkedHashMap<>();
        // 主表字段
        for (String field : TASK_FIELDS) {
            if (map.containsKey(field)) result.put(field, map.get(field));
        }
        // 工匠字段
        for (String field : CRAFTSMAN_FIELDS) {
            if (map.containsKey(field)) craftsman.put(field.substring(10), map.get(field));
        }
        // 其他字段补充
        for (String key : map.keySet()) {
            if (!result.containsKey(key) && !key.startsWith("craftsman_")) {
                result.put(key, map.get(key));
            }
        }
        if (!craftsman.isEmpty()) result.put("craftsman", craftsman);
        return result;
    }
} 